﻿(function () {
    "use strict";

    function init(key, q, title, subtitle, description) {
        this.key = key;
        this.q = q;
        this.title = title;
        this.subtitle = subtitle;
        this.description = description;
    }

    var instanceMembers = {
        getFeed: function () {
            var today = new Date();

            var feed = {
                backgroundImage: "https://twitter.com/images/resources/twitter-bird-white-on-blue.png",
                description: this.description,
                key: this.key,
                logoUrl: "https://twitter.com/images/resources/twitter-bird-white-on-blue.png",
                pubDate: today.getDay + "-" + today.getMonth + "-" + today.getFullYear(),
                subtitle: this.subtitle,
                title: this.title,
                url: "http://search.twitter.com/search.json?q=" + this.q,
            };

            return WinJS.xhr({ url: feed.url }).then(function (response) {
                var result = JSON.parse(response.responseText);
                var feedItems = [];
                var postIndex = 0;

                result.results.forEach(function (tweet) {
                    var feedItem = {
                        author: tweet.from_user_name,
                        backgroundImage: tweet.profile_image_url,
                        content: "",
                        group: feed,
                        key: tweet.text,
                        link: "https://twitter.com/" + tweet.from_user + "/status/" + tweet.id_str,
                        postIndex: postIndex,
                        pubDate: tweet.created_at.replace(" +0000", ""),
                        title: tweet.from_user + ": " + tweet.text
                    };
                    feedItems.push(feedItem);
                    postIndex++;
                })

                return WinJS.Promise.wrap(feedItems);
            });
        },
    };

    var staticMembers = {};

    var TwitterQuery = WinJS.Class.define(init, instanceMembers, staticMembers);

    // add to namespace
    WinJS.Namespace.define("Queries",
        {
            TwitterQuery: TwitterQuery
        }
    );
})();